package aar.test.tessocr;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.adapter.CabDetailAdapter;
import aar.test.tessocr.adapter.CompanySearchInfoAdapter;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CabDetailModel;
import aar.test.tessocr.model.CabinetModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.tessOcrUtil.MyGridView;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.statuesBar;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.LoginActivity.JSON;

public class ChioceCabActivity extends AppCompatActivity {


    private RadioGroup gridRadioGroup;

    private Button open_grid;

    private TextView choiceCab_spinner;
    private TextView choiceCab_spinner2;


    private List<CabinetModel> cabList;

    private List<String> data_list = new ArrayList<>();

    private int selectId = 0;

    private int cabType = 1;

    private ArrayAdapter<String> cabAdater;

    private Context mContext;

    private DisplayMetrics dm;

    private boolean isPerss=false;

    private  Toolbar toolbar;

    private MyGridView cab_grid_view;

    private LinearLayout left_layout;

    private Button cab_open_all;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chioce_cab);
        mContext=this;


        toolbar = (Toolbar) findViewById(R.id.toolbar_normal);
        setSupportActionBar(toolbar);
        initView();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);




        if (Build.VERSION.SDK_INT >= 23) {
            requestP();

        }





        companyCabDetail();
    }


    private void initView(){


        cab_open_all=findViewById(R.id.cab_open_all);
        cab_open_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                openAllCab();

            }
        });



        cab_grid_view=findViewById(R.id.cab_grid_view);

        cab_grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


               if(null!=mList&&mList.size()>0){

                    BaseApplication.getIntance().setmCabDetailModel(mList.get(position));
                   startActivity(new Intent(ChioceCabActivity.this, CabInfoActivity.class));
               }




            }
        });

        left_layout=findViewById(R.id.left_layout);
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private List<CabDetailModel> mList;
    private void companyCabDetail(){
        if(null==BaseApplication.getIntance().getLoginBean()){
            return;
        }if(null==BaseApplication.getIntance().getLoginBean().getCabinetId()){
            return;
        }

        Map<String ,Object> map=new HashMap<>();
        map.put("cabinetId",BaseApplication.getIntance().getLoginBean().getCabinetId());
        map.put("adminid",BaseApplication.getIntance().getLoginBean().getId());

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse<List<CabDetailModel>>>post(Urls.URL_CABINETDETAIL)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<CabDetailModel>>>(ChioceCabActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<CabDetailModel>>> response) {


                        Log.e("MainActivity","onSuccess-----logout---------------");

                        if(null!=response.body().data&&response.body().data.size()>0){
                            mList=new ArrayList<>();
                            mList=response.body().data;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    cab_grid_view.setVisibility(View.VISIBLE);
                                    CabDetailAdapter adapter = new CabDetailAdapter(mContext,mList);
                                    cab_grid_view.setAdapter(adapter);


                                }
                            });
                        }else{


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    cab_grid_view.setVisibility(View.GONE);
                                }
                            });



                        }





                    }

                    @Override
                    public void onError(Response<LzyResponse<List<CabDetailModel>>> response) {
                        Log.e("MainActivity","onError---------------------");
                    }
                });



    }




    private void openAllCab(){

        if(null==BaseApplication.getIntance().getLoginBean()){
            return;
        }

        if(null==BaseApplication.getIntance().getLoginBean().getCabinetId()){
            return;
        }

        Map<String ,Object> map=new HashMap<>();
        map.put("cabinetId",BaseApplication.getIntance().getLoginBean().getCabinetId());
        map.put("type",1);

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse>post(Urls.URL_ADMINOPENGRID)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse>(ChioceCabActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse> response) {


                        Log.e("MainActivity","onSuccess-----logout---------------"+response.body().data);


                        if(null!=response.body().msg){
                            Toast.makeText(mContext,response.body().msg,Toast.LENGTH_LONG).show();
                        }


                    }

                    @Override
                    public void onError(Response<LzyResponse> response) {
                        Log.e("MainActivity","onError---------------------");
                        if(null!=response.body().msg){
                        Toast.makeText(mContext,response.body().msg,Toast.LENGTH_LONG).show();}
                    }
                });



    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);

    }



    private void requestP() {

        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission( Manifest.permission.CAMERA)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).
                                show();
                    }
                })
                .start();
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();

                    isPerss=true;
                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    isPerss=false;
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(ChioceCabActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(ChioceCabActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };




}
